package action;

import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.IRouts;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import form.AdminRoutsForm;
import service.RoutsService;
import service.RoutsStantionService;
import service.ServiceManager;

public class AdminRoutsAction extends ConnectionAwareAction    {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		AdminRoutsForm input = (AdminRoutsForm) form;

		RoutsService routsService = ServiceManager.getDefault().getRoutsService();
		RoutsStantionService routsStantionService = ServiceManager.getDefault().getRoutsStantionService();
   	 
		int[] id_check_routs = input.getId_check_routs();
		int[] id_check_city = input.getId_check_city();
		String[] name_routs = input.getName_routs();
		String[] date_routs = input.getDate_routs();
		String add_name = null; 
		String add_date = input.getAdd_date();
		
    	if (request.getParameter("add_routs")!=null){
    		if (add_name != "" && add_date != ""){
    			add_name = input.getAdd_name();
    			routsService.setRouts(add_name, add_date);
    		}
    	}
    	
    	if (request.getParameter("Updat") !=null){  	
    		if(id_check_routs != null){
    			List<IRouts> routsUp = routsService.getRoutsById(id_check_routs); 
    			request.setAttribute("routsUp", routsUp);
    		}
    	}
    	
    	if (request.getParameter("UpdateRouts") !=null){
    		if(id_check_routs !=null && name_routs != null){
    			routsService.setRoutsUpdate(id_check_routs, name_routs, date_routs);
    			id_check_routs = null;
    			id_check_city = null;
    			input.reset(id_check_routs, id_check_city);
    		}
    	}
    	
    	if (request.getParameter("Delete") != null){
			if (id_check_routs !=null){
				routsService.delete(id_check_routs);
				routsStantionService.deleteOrder(id_check_routs);
			}
			if (id_check_city !=null){
				routsStantionService.delete(id_check_city);
			}
			id_check_routs = null;
			id_check_city = null;
			input.reset(id_check_routs, id_check_city);
		}	
    	
    	List<IRouts> routs = routsService.getRouts();
    	List<IRouts> routsstantion = routsService.getRoutsStantion();

    	request.setAttribute("routs", routs);
    	request.setAttribute("routsstantion", routsstantion);
		return mapping.findForward(ForwardActionTo.SUCCESS);
	}
}
